# encoding = utf-8

import pandas as pd

from application.data_process.calc_weighted_temper import func_calc_weighted_temper
from application.data_process.data_process_instant.Temperture_Missing_value import Temperature_Missing_value
from application.data_process.get_area_code import func_get_area_code
from application.data_process.read_inside_temperature_data import \
    func_read_inside_temperature_data
from application.data_process.read_station_data import func_read_station_data
from application.data_process.read_station_id_model_name import read_station_id_model_name
from application.logging import logger
from application.utils.CodeTimingUtil import CodeTimingUtil
from application.utils.DatabasePrimaryKeyGeneratorUtil import DatabasePrimaryKeyGeneratorUtil
from application.utils.MySQLUtils import MySQLUtils


@CodeTimingUtil(name="数据预处理[瞬热][func_main_data_process_instance]")
def func_main_data_process_instance():
    """
    数据预处理:瞬热
    :return:
    """
    #
    # 读取数据
    station_id_name = read_station_id_model_name()
    logger.info(f"读取数据:\n {station_id_name}")
    #
    #
    station_id_list = list(station_id_name["station_id"])
    logger.info(f"热力站编号列表[station_id_list][{len(station_id_list)}]:\n {station_id_list}")
    #
    # for ->
    for j_name, station_id in enumerate(station_id_list):
        #
        # 打印数据
        logger.info(f"热力站编号: {station_id}")

        #
        # 查询数据
        station_data = func_read_station_data(station_id=station_id, data_type="instant")
        logger.info(f"历史工况数据[station_data]:\n {station_data}")

        #
        # if ->
        if station_data is not None:
            """
            sn_control_model_station: 历史工况表
            status_instant: 数据处理状态, 0-未处理, 1-正处理, 2-已处理
            """
            # 更新语句 # TODO 更新数据处理状态，更新的是所有数据，如果更新是有数据上传，会导致数据丢失
            sql = f"UPDATE sn_control_model_station SET status_instant=1 WHERE status_instant=0"
            # 打印数据
            logger.info(f"更新语句[处理中]: {sql}")
            # 获取链接
            con = MySQLUtils.get_mysql_connection()
            # 获取游标
            cur = con.cursor()
            # 执行更新
            cur.execute(sql)
            # 提交事务
            con.commit()
            # 关闭游标
            cur.close()
            # 关闭链接
            con.close()
            pass  # if <-
        #
        # 地区编码
        area_code = func_get_area_code(station_id=station_id)
        logger.info(f"地区编码[area_code]: {area_code}")

        #
        # 数据补齐:室外天气
        station_data_add_temp: pd.DataFrame = Temperature_Missing_value(
            model_name_temp=f"cha_zhi_cubic_{area_code}.pkl",
            model_name_humidity=f"cha_zhi_cubic_humidity_{area_code}.pkl",
            model_name_weather=f"cha_zhi_cubic_weather_{area_code}.pkl",
            model_name_wind=f"cha_zhi_cubic_wind_{area_code}.pkl",
            station_data=station_data
        )
        logger.info(f"补齐天气数据结束[station_data_add_temp]: \n {station_data_add_temp}")

        #
        # 查询数据:室内温度
        dict_temperature = func_read_inside_temperature_data(station_id)
        # logger.info(f"室内温度时间列表:\n {dict_temperature.keys()}")

        #
        # if ->
        if (station_data_add_temp is None) or station_data_add_temp.empty:
            logger.error(f"数据库中没有可处理的数据或补齐数据出错")
            return
            pass  # <- if
        else:
            # station_data_add_temp.reset_index(drop=True, inplace=True)
            #
            shi_nei_wen_du = []
            station_data_add_temp_enum = enumerate(station_data_add_temp['collect_time'])
            logger.info(f"station_data_add_temp_enum: {station_data_add_temp_enum}")

            #
            # for ->
            for i, _ in station_data_add_temp_enum:
                # 打印数据:采集时间
                # print(_)
                # 时间处理:截取前13位
                Time1 = str(_)[:13]
                # print(Time1)
                # if ->
                if Time1 in dict_temperature:
                    # print(f"时间匹配:是")  # TODO 未打印时间匹配数据
                    # 室温平均:加权平均
                    tem = func_calc_weighted_temper(dict_temperature[Time1])
                    shi_nei_wen_du.append(tem)
                    pass  # <- if
                # else ->
                else:
                    #
                    # print(f"时间匹配:否:{i}")
                    # 删除数据
                    station_data_add_temp = station_data_add_temp.drop(index=[i])
                    pass  # <- else
                pass  # <- for
            #
            #
            logger.info(f"加权均值室温[shi_nei_wen_du][len]: {len(shi_nei_wen_du)}")
            # logger.info(f"加权均值室温列表[shi_nei_wen_du]:\n {shi_nei_wen_du}")

            #
            # 重置索引
            station_data_add_temp.reset_index(drop=True, inplace=True)

            #
            # 加权平均:室内温度
            station_data_add_temp['average_inside_temper'] = shi_nei_wen_du
            logger.info(f"添加平均室温数据列[station_data_add_temp]: \n {station_data_add_temp}")

            #
            # 筛选数据
            data = station_data_add_temp[
                [
                    "collect_time",  # 采集时间
                    "outside_temper",  # 室外温度
                    "outside_humidity",  # 室外湿度
                    "outside_weather",  # 室外天气
                    "outside_wind",  # 室外风速
                    "average_inside_temper",  # 平均室温:室内
                    "second_supply_water_temp",  # 二次供水温度
                    "second_back_water_temp",  # 二次回水温度
                    "total_instant_heat"  # 瞬时热量
                ]
            ]
            #
            # 打印数据
            logger.info(f"筛选数据结果:\n {data}")

            #
            con = MySQLUtils.get_mysql_connection()
            cur = con.cursor()

            #
            # 数据入库
            for i in range(len(data)):
                #
                # 返回结果
                id_ = DatabasePrimaryKeyGeneratorUtil.generate()
                logger.info(f"id:{id_}")
                #
                #
                sql = f"INSERT INTO `sn_control_model_station_instant_transition`" \
                      f"(id,station_id,model_name,collect_time,outside_temper," \
                      f"outside_wind,outside_weather,outside_humidity,average_inside_temper," \
                      f"supply_water_temper,back_water_temper,instant_heat) " \
                      f"VALUES (%d,%d,\'%s\',str_to_date(\'%s\','%%Y-%%m-%%d %%H:%%i:%%s'), " \
                      f"%f,%d,%d,%f,%f,%f,%f,%f)" \
                      % \
                      (
                          id_,
                          station_id,
                          list(station_id_name["model_name"])[j_name],
                          data.iloc[i]["collect_time"],
                          data.iloc[i]["outside_temper"],
                          data.iloc[i]["outside_wind"],
                          data.iloc[i]["outside_weather"],
                          data.iloc[i]["outside_humidity"],
                          data.iloc[i]["average_inside_temper"],
                          data.iloc[i]["second_supply_water_temp"],
                          data.iloc[i]["second_back_water_temp"],
                          data.iloc[i]["total_instant_heat"]
                      )
                #
                cur.execute(sql)
                #
                # 每10条提交一次事务
                if i % 10 == 0:
                    con.commit()
                    pass
                pass  # for <-

            #  更新处理状态
            update_sentence2 = "update sn_control_model_station set status_instant=2 where status_instant=1 "
            cur.execute(update_sentence2)
            con.commit()
            cur.close()
            con.close()
            pass
        pass
    pass  # for <- -----------------------------------------------------------------------------------------------------


pass  # end of function

if __name__ == '__main__':
    func_main_data_process_instance()
    pass
